<template>
	<view style="padding-bottom: 150rpx;" class="wrapper bg-linear">
		<view class="wrapper shadow1 border-r-10 bg-color m-b-8 p-8">
			<ppl-textarea placeholder="请输入您的详细需求" @onChange="onChangeNeed">
				<view slot="title" class="t-14">填写信息</view>
			</ppl-textarea>
			<ppl-upload @afterRead="afterRead" />
			<ppl-infoField :use-custom="true">
				<view>
					<van-field :value="address" :required="true" placeholder="请选择收货地址" error-message-align="right"
						:error-message="errors.address" is-link clickable readonly input-align="right"
						@click-input="toSelectAddress">
						<view slot="label" class="color8">
							收货地址
						</view>
					</van-field>
					<van-field :value="bonus" :required="true" placeholder="输入金额" error-message-align="right"
						:error-message="errors.bonus" input-align="right" @change="onChangeBonus">
						<view slot="label" class="color8">
							金额
						</view>
					</van-field>
				</view>
			</ppl-infoField>
		</view>
		<ppl-tips :tips="tips" />
		<ppl-pay @submit="submit" :price="price" />
		<ppl-kd :show="showSelectors" @close="close" @onSelected="onSelected" position="bottom" />
		<van-popup :show="show" @close="show = false" position="bottom">
			<van-picker :show-toolbar="true" :columns="columns" @change="onChangeTime" @confirm="confirmTime" />
		</van-popup>
	</view>
</template>

<script setup>
	import {
		onLoad,
		onShow,
		onUnload
	} from '@dcloudio/uni-app';
	import {
		ref,
		reactive,
		watch,
		computed
	} from 'vue'
	import {
		getGoodsSize,
		postNeed
	} from '@/api/index.js'
	import {
		DELIVERYTIME,
		GENDER
	} from '@/package/constants/index.js'
	import {
		getList,
		payFlag
	} from '@/utils/index.js'
	import {
		addCampusOrder
	} from '@/package/api/insertList.js'
	import {
		getPaymentInfoTo,
		getYueZhiFu
	} from '@/api/index.js'

	import {
		updateCampusOrder,
		deleteCampusOrder
	} from '@/package/api/update.js'

	// 地址相关响应式数据
	const address = ref(''); // 收货地址
	let addressListener = null; // 存储收货地址事件监听器引用

	// 获取当前用户ID
	const userId = ref(uni.getStorageSync('userId') || '');

	// 初始化所有响应式数据
	const checked = ref(true)
	const bonus = ref('')
	const price = ref(0);
	const cid = ref('');
	const name = ref('');
	const showSelectors = ref(false);
	const show = ref(false)
	const columns = ref([]);
	const currentSelect = ref('');
	const need = ref('');
	const tips = ref(['发布需要实名认证审核通过'])
	const errors = reactive({
		address: '',
		bonus: ''
	});

	// 图片相关数据（关键修改点）
	const imageUrls = ref([]); // 存储图片URL数组
	const imgs = computed(() => imageUrls.value.join(',')); // 生成逗号分隔字符串

	// 生成唯一订单号
	const generateOrderNo = () => {
		const timestamp = new Date().getTime();
		const randomNum = Math.floor(Math.random() * 1000);
		const schoolId = uni.getStorageSync('school_id') || '000';
		return `ORD${schoolId}${timestamp}${randomNum}`;
	}

	// 价格计算
	const updatePrice = () => {
		price.value = bonus.value ? Number(bonus.value) : 0;
	}

	// 金额变更
	const onChangeBonus = (e) => {
		bonus.value = e.detail;
		if (bonus.value) errors.bonus = '';
		updatePrice();
	}

	// 选择地址
	const toSelectAddress = () => {
		console.log('准备跳转到收货地址选择页面');

		// 移除旧监听器
		if (addressListener) {
			uni.$off('selectAddress', addressListener);
			uni.$off('selectPickAddress', addressListener);
			addressListener = null;
		}

		// 新建监听器
		addressListener = (res) => {
			if (res && (res.building || res.detailAddress)) {
				address.value = `${res.building || ''} ${res.detailAddress || ''}`.trim();
				errors.address = '';
			} else if (res && res.address) {
				address.value = res.address;
				errors.address = '';
			} else {
				console.error('地址选择返回数据格式异常:', res);
			}
		};

		// 绑定事件
		uni.$on('selectAddress', addressListener);
		uni.$on('selectPickAddress', addressListener);

		// 跳转地址页
		uni.navigateTo({
			url: '/package/pages/address/address?isPickAddress=true',
			success: () => console.log('成功跳转地址页'),
			fail: (err) => console.error('跳转失败:', err)
		});
	}

	// 关闭弹窗
	const close = () => {
		showSelectors.value = false;
	}

	// 需求变更
	const onChangeNeed = (e) => {
		need.value = e.detail;
	}

	// 图片上传处理（关键修改点）
	const afterRead = (res) => {
		console.log('图片上传结果:', res);

		if (!res || !Array.isArray(res.value) || res.value.length === 0) {
			imageUrls.value = []; // 清空数组
			console.log('未上传图片或上传失败');
			return;
		}

		// 提取图片URL并过滤无效项
		const validUrls = res.value
			.map(item => {
				if (!item) return '';
				// 优先使用fullurl，其次urlKey
				return item.fullurl || item.urlKey || '';
			})
			.filter(url => url.trim() !== ''); // 过滤空字符串

		imageUrls.value = validUrls; // 存储URL数组
		console.log('处理后的图片URL数组:', imageUrls.value);
		console.log('处理后的图片URL字符串:', imgs.value);

		// 保存到本地存储，防止页面跳转丢失
		uni.setStorageSync('tempImages', imageUrls.value);
	};

	// 提交订单
	const submit = async () => {
		// 表单验证
		if (!address.value) {
			errors.address = '请选择收货地址';
			return;
		}
		if (!bonus.value) {
			errors.bonus = '请输入金额';
			return;
		}

		// 从本地存储中获取查看是否实名
		if (uni.getStorageSync('isrealnameauthenticated') != 1) {
			// 表示未实名
			uni.showToast({
				title: '未进行实名认证,不能发布任务',
				icon: 'none',
				duration: 1000
			});
			return
		}

		try {
			// 构建订单参数（使用计算属性生成的字符串）
			const campusOrder = {
				orderNo: generateOrderNo(),
				orderType: 6, // 代写服务
				orderStatus: 0,
				payAmount: price.value.toString(),
				payStatus: 0,
				endPlace: address.value,
				phone: uni.getStorageSync('userPhone') || '',
				imageInfo: imgs.value, // 直接使用逗号分隔的字符串
				pickupInfo: need.value,
				schoolId: uni.getStorageSync('school_id'),
				userId: userId.value
			};

			console.log('提交的订单参数:', JSON.stringify(campusOrder));

			// 调用API
			const addRes = await addCampusOrder(JSON.stringify(campusOrder));
			console.log('订单添加响应:', addRes);

			if (addRes.data > 0) {
				// 显示支付方式
				uni.showActionSheet({
					itemList: ['微信支付', '余额支付'],
					success: (res) => {
						switch (res.tapIndex) {
							case 0:
								handleWechatPay(campusOrder.orderNo, addRes.data);
								break;
							case 1:
								handleBalancePay(campusOrder.orderNo, addRes.data);
								break;
						}
					},
					fail: (err) => {
						console.log('支付方式显示失败:', err);
						//handleWechatPay(campusOrder.orderNo, addRes.data);
					}
				});
			} else {
				uni.showToast({
					title: addRes.msg || '订单添加失败',
					duration: 1000,
					icon: 'none'
				});
			}
		} catch (e) {
			console.error('订单提交异常:', e);
			uni.showToast({
				title: '操作失败，请重试',
				duration: 1000,
				icon: 'none'
			});
		}
	}

	// 余额支付
	const handleBalancePay = async (orderNo, orderId) => {
		try {
			const payParams = {
				orderNo: orderNo,
				totalAmount: price.value.toFixed(2)
			};

			uni.showLoading({
				title: '支付处理中...'
			});
			const payRes = await getYueZhiFu(payParams);
			uni.hideLoading();

			if (payRes.code === 200) {
				uni.showModal({
					title: '支付结果',
					content: payRes.message || '余额支付成功',
					success: () => {
						// 更新订单状态
						updateCampusOrder({
							orderNo,
							payStatus: 1,
							orderStatus: 1,
							paymentType: 1
						});
						resetForm();
						// uni.switchTab({
						// 	url: '/pages/index/index'
						// });
					}
				});
			} else if (payRes.code === 400) {
				uni.showToast({
					title: '余额不足',
					icon: 'none'
				});
				deleteCampusOrder(JSON.stringify({
					id: orderId
				}));
			}
		} catch (error) {
			console.error('余额支付异常:', error);
			uni.showToast({
				title: '支付处理失败',
				icon: 'none'
			});
		}
	};

	// 微信支付
	const handleWechatPay = async (orderNo, orderId) => {
		try {
			const payData = {
				orderNo
			};
			const payRes = await getPaymentInfoTo(payData);

			if (payRes.code === 200) {
				wx.requestPayment({
					...payRes.data.jsConfig,
					success: () => {
						updateCampusOrder({
							orderNo,
							payStatus: 1,
							orderStatus: 1,
							paymentType: 0
						});
						resetForm();
					},
					fail: () => {
						deleteCampusOrder(JSON.stringify({
							id: orderId
						}));
					}
				});
			}
		} catch (error) {
			console.error('微信支付异常:', error);
			uni.showToast({
				title: '支付处理失败',
				icon: 'none'
			});
		}
	};

	// 重置表单
	const resetForm = () => {
		address.value = '';
		bonus.value = '';
		need.value = '';
		imageUrls.value = []; // 清空图片数组
		price.value = 0;
		Object.keys(errors).forEach(key => errors[key] = '');
		uni.removeStorageSync('tempImages'); // 清除临时存储
	};

	// 生命周期钩子（关键修改点）
	onShow(() => {
		if (!userId.value) userId.value = uni.getStorageSync('userId') || '';

		// 从本地存储恢复图片数据
		const savedImages = uni.getStorageSync('tempImages');
		if (savedImages && Array.isArray(savedImages)) {
			imageUrls.value = savedImages;
			console.log('从本地存储恢复图片数据:', imageUrls.value);
		}
	});

	onLoad((options) => {
		name.value = options.name || '';
		cid.value = options.cid || '';
		if (!userId.value) userId.value = uni.getStorageSync('userId') || '';

		// 从本地存储恢复图片数据
		const savedImages = uni.getStorageSync('tempImages');
		if (savedImages && Array.isArray(savedImages)) {
			imageUrls.value = savedImages;
			console.log('页面加载时恢复图片数据:', imageUrls.value);
		}
	});

	onUnload(() => {
		if (addressListener) {
			uni.$off('selectAddress', addressListener);
			uni.$off('selectPickAddress', addressListener);
			addressListener = null;
		}

		// 保存图片数据到本地存储
		uni.setStorageSync('tempImages', imageUrls.value);
	});
</script>

<style scoped>
	::v-deep .van-cell {
		padding-left: 0;
		padding-right: 0;
	}

	::v-deep .van-submit-bar__bar {
		justify-content: space-between;
	}

	::v-deep .van-button--danger {
		background-color: #3c91ff;
		border-radius: 10rpx;
	}

	::v-deep .van-submit-bar__bar {
		box-shadow: -2px -1px 5px 0px rgba(0, 0, 0, 0.05);
	}

	::v-deep .input-placeholder {
		color: #3c91ff !important;
	}

	::v-deep .van-cell--required:before {
		left: -7px;
	}

	::v-deep .van-cell:after {
		right: 0;
		left: 0;
	}

	.express-size-btn {
		width: 70px;
		height: 40px;
		line-height: 40px;
		border-radius: 20rpx;
		border: 1px solid #ddd;
		font-size: 22rpx;
		color: #666;
		white-space: nowrap;
		text-align: center;
		background-color: #fff;
		float: left;
		margin-right: 10px;
	}

	.express-size-btn.active {
		border-color: #3c91ff;
		color: #3c91ff;
		background-color: rgba(60, 145, 255, 0.1);
	}
</style>